# Copyright 2010 Aritus Computer Services, L.L.C.
# Author: Greg McMurray
# License: Dunno

# Grabs variables from the URL to configure output engine
# /Sheets/{Operation}/{Seed}
# Other potential options: max value for both numbers, as well as answer
import os
import re
import random
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

BASE_URL = '/Sheets/(\w+)/?'
SEED_URL = '\d+$'

class SubtractionPage(webapp.RequestHandler):
    def get(self):
        #self.response.out.write(self.request.url)
        # check for a missing seed value, create one and redirect
        if re.search(BASE_URL + '$', self.request.url, re.I):
            return self.redirect('/Sheets/Subtraction/%s' % (random.randint(1,32767)))
        
        # get seed value from URL
        if re.search(SEED_URL, self.request.url):
            seed = int(re.search(SEED_URL, self.request.url).group(0))
            random.seed(seed)
            
            data = []
            for row in range(0,10):
                row = [[random.randint(0,10),random.randint(0,20)] for x in range(10)]
                for cell in row:
                    cell.sort()
                data.append(row)
            
            template_values = {
                'title': re.search(BASE_URL, self.request.url).group(1),
                'seed': seed,
                'data': data
            }
            
            self.response.headers['Content-Type'] = 'text/html'
            path = os.path.join(os.path.join(os.path.dirname(__file__), 'templates'), '10x10.html') 
            html = template.render(path, template_values)
            self.response.out.write(html)
        else:
            self.response.out.write(self.request.url)


application = webapp.WSGIApplication([('/Sheets/Subtraction/?\d*', SubtractionPage)], debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()
